package com.epfresh.supplier.location;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.district.DistrictResult;
import com.baidu.mapapi.search.district.DistrictSearch;
import com.baidu.mapapi.search.district.DistrictSearchOption;
import com.baidu.mapapi.search.district.OnGetDistricSearchResultListener;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.supplier.R;
import com.epfresh.supplier.entity.Address;
import com.epfresh.supplier.entity.CityAddressList;
import com.epfresh.supplier.entity.CityMap;
import com.epfresh.supplier.view.AreaDialog;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

public class PoiAddressActivity extends BaseActivity implements BDLocationListener, OnGetGeoCoderResultListener, BaiduMap.OnMapStatusChangeListener, TextWatcher {
    EditText etContent;
    TextView tvSearch;
    TextView tvCity;
    ImageView ivLocation;
    /**
     * 搜索输入框对应的ListView
     */
    private ListView lvSearch;
    private ListView lv;
    private RelativeLayout rlMap;
    PoiAdapter poiAdapter;
    PoiSearchAdapter poiSearchAdapter;

    List<PoiInfo> poiInfo = new ArrayList<>();
    List<PoiInfo> poiInfos = new ArrayList<>();
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    /**
     * 定位模式
     */
    private MyLocationConfiguration.LocationMode mCurrentMode;
    /**
     * 定位端
     */
    private LocationClient mLocClient;
    /**
     * 是否是第一次定位
     */
    private boolean isFirstLoc = true;
    /**
     * 定位坐标
     */
    private LatLng locationLatLng;
    /**
     * 定位城市
     */
    private String city;
    /**
     * 反地理编码
     */
    private GeoCoder geoCoder;

    private boolean isLimit;
    private boolean isFirstCity;
    private String cityDataStr;


    String cityName;
    String lat;
    String lng;

    //
    boolean isAddress = true;


    protected View getToolBar() {
        View actionbar = this.inflaterView(R.layout.toolbar_map_search, (ViewGroup) null);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(-1, this.getResources().getDimensionPixelSize(com.epfresh.api.R.dimen.action_bar_height));
        actionbar.setLayoutParams(lp);
        return actionbar;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //在使用SDK各组件之前初始化context信息，传入ApplicationContext
        //注意该方法要再setContentView方法之前实现
        SDKInitializer.initialize(getApplicationContext());
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_poi_address);
        if (savedInstanceState != null) {
            getIntent().putExtra("isLimit", savedInstanceState.getBoolean("isLimit", false));
            getIntent().putExtra("cityData", savedInstanceState.getString("cityData"));

            getIntent().putExtra("cityName", savedInstanceState.getString("cityName"));
            getIntent().putExtra("lat", savedInstanceState.getString("lat"));
            getIntent().putExtra("lng", savedInstanceState.getString("lng"));
        }

        cityName = getIntent().getStringExtra("cityName");
        Log.e("cityName", "cityName:" + cityName);
        lat = getIntent().getStringExtra("lat");
        lng = getIntent().getStringExtra("lng");

        if (getAddressLatLng() != null) {
            isAddress = true;
        }
        isLimit = getIntent().getBooleanExtra("isLimit", false);
//        if (isLimit) {
        cityDataStr = getIntent().getStringExtra("cityData");
        if (cityDataStr != null) {
            cityData = new Gson().fromJson(cityDataStr, CityMap.class);
        }
//        }
        initView();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putBoolean("isLimit", isLimit);
        outState.putString("cityData", cityDataStr);
        outState.putString("cityName", cityName);
        outState.putString("lat", lat);
        outState.putString("lng", lng);
        super.onSaveInstanceState(outState);
    }

    private void initView() {
        ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        etContent = (EditText) findViewById(R.id.et_content);
        tvSearch = (TextView) findViewById(R.id.tv_search);
        tvCity = (TextView) findViewById(R.id.tv_city);
        ivLocation = (ImageView) findViewById(R.id.iv_location);
        //文本输入框改变监听，必须在定位完成之后
        etContent.addTextChangedListener(this);
        tvCity.setOnClickListener(this);
        etContent.setOnClickListener(this);
        ivLocation.setOnClickListener(this);

        mMapView = (MapView) findViewById(R.id.b_map);
        mBaiduMap = mMapView.getMap();

        lv = (ListView) findViewById(R.id.lv);

        rlMap = (RelativeLayout) findViewById(R.id.rl_map);


        lvSearch = (ListView) findViewById(R.id.lv_search);
        poiAdapter = new PoiAdapter(PoiAddressActivity.this, poiInfo);
        lv.setAdapter(poiAdapter);

        poiSearchAdapter = new PoiSearchAdapter(PoiAddressActivity.this, poiInfos, locationLatLng);

        lvSearch.setAdapter(poiSearchAdapter);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (i < poiInfo.size()) {

//                    if (isLimit) {
                    showProgressDialog();
                    verifyAddress(poiInfo.get(i));
//                    }else {
//                        loadAddress(poiInfo.get(i));
//                    }
                }
            }
        });
        lvSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (i < poiInfos.size()) {

//                    if (isLimit) {
                    showProgressDialog();
                    verifyAddress(poiInfos.get(i));
//                    }else {
//                        loadAddress(poiInfos.get(i));
//                    }
                }
            }
        });
        city = ApplicationHelper.getInstance().getCity().getCityName();
        tvCity.setText(ApplicationHelper.getInstance().getCity().getCityName());


        //定义地图状态
        MapStatus mMapStatus = new MapStatus.Builder().zoom(18).build();
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        //改变地图状态
        mBaiduMap.setMapStatus(mMapStatusUpdate);

        //地图状态改变相关监听
        mBaiduMap.setOnMapStatusChangeListener(this);

        //开启定位图层
        mBaiduMap.setMyLocationEnabled(true);

        //定位图层显示方式
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;

        /**
         * 设置定位图层配置信息，只有先允许定位图层后设置定位图层配置信息才会生效
         * customMarker用户自定义定位图标
         * enableDirection是否允许显示方向信息
         * locationMode定位图层显示方式
         */
        mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(mCurrentMode, true, null));
        //创建GeoCoder实例对象
        geoCoder = GeoCoder.newInstance();
        //设置查询结果监听者
        geoCoder.setOnGetGeoCodeResultListener(this);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                ) {

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    0x1991);
        } else if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                ) {

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    0x1993);
        } else {
            initLocation();
        }
        LatLng addressLatLng = getAddressLatLng();
        if (addressLatLng != null) {
            isFirstCity = false;
            MapStatusUpdate msu = MapStatusUpdateFactory.newLatLngZoom(addressLatLng, 18);
            mBaiduMap.animateMapStatus(msu);
            if (geoCoder != null) {
                geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(addressLatLng));
            }
            city = cityName;
            tvCity.setText(cityName);
        } else {
            isAddress = false;
            isFirstCity = true;
        }


//        address.setCityId(ApplicationHelper.getInstance().getCity().getCityId());

    }

    private void initLocation() {
        //初始化定位
        mLocClient = new LocationClient(this);
        //注册定位监听
        mLocClient.registerLocationListener(this);

        //定位选项
        LocationClientOption option = new LocationClientOption();
        /**
         * coorType - 取值有3个：
         * 返回国测局经纬度坐标系：gcj02
         * 返回百度墨卡托坐标系 ：bd09
         * 返回百度经纬度坐标系 ：bd09ll
         */
        option.setCoorType("bd09ll");
        //设置是否需要地址信息，默认为无地址
        option.setIsNeedAddress(true);
        //设置是否需要返回位置语义化信息，可以在BDLocation.getLocationDescribe()中得到数据，ex:"在天安门附近"， 可以用作地址信息的补充
        option.setIsNeedLocationDescribe(true);
        //设置是否需要返回位置POI信息，可以在BDLocation.getPoiList()中得到数据
        option.setIsNeedLocationPoiList(true);
        /**
         * 设置定位模式
         * Battery_Saving
         * 低功耗模式
         * Device_Sensors
         * 仅设备(Gps)模式
         * Hight_Accuracy
         * 高精度模式
         */
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //设置是否打开gps进行定位
        option.setOpenGps(true);
        //设置扫描间隔，单位是毫秒 当<1000(1s)时，定时定位无效
        option.setScanSpan(1000);

        //设置 LocationClientOption
        mLocClient.setLocOption(option);

        //开始定位
        mLocClient.start();


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 0x1993:
            case 0x1991: {
                // If requestSilent is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initLocation();
                } else {
                    if (!isAddress) {
                        toast("定位失败，请手动输入地址");
                        isFirstCity = false;
                        locationFail();
                    }
                }
                return;
            }

        }
    }

    public void loadAddress(PoiInfo poiInfo) {
        LatLng location = poiInfo.location;
        String city = poiInfo.city;
        String address = poiInfo.address;
        int i = poiInfo.describeContents();
        String name = poiInfo.name;
        String postCode = poiInfo.postCode;


        if (address == null) {
            address = "";
        }
        Log.v("location", "location:" + location.latitude + "--" + location.longitude);
        Log.v("location", "name:" + name);
        Log.v("location", "city:" + city);
        Log.v("location", "address:" + address);
        Log.v("location", "postCode:" + postCode);
        Log.v("location", "getProvinceName:" + this.address.getProvinceName());
        Log.v("location", "getCityName:" + this.address.getCityName());
        Log.v("location", "getDistrictName:" + this.address.getDistrictName());

        Log.v("location", "getProvinceId:" + this.address.getProvinceId());
        Log.v("location", "getCityId:" + this.address.getProvinceId());
        Log.v("location", "getDistrictId:" + this.address.getProvinceId());


        Intent intent = new Intent();

        intent.putExtra("detail_address", name);
        intent.putExtra("address", address);

        intent.putExtra("latitude", location.latitude + "");
        intent.putExtra("longitude", location.longitude + "");

        intent.putExtra("provinceName", this.address.getProvinceName());
        intent.putExtra("cityName", this.address.getCityName());
        intent.putExtra("DistrictName", this.address.getDistrictName());

        intent.putExtra("provinceId", this.address.getProvinceId());
        intent.putExtra("cityId", this.address.getCityId());
        intent.putExtra("DistrictId", this.address.getDistrictId());


        intent.putExtra("poi_address", name + address + "|" + location.latitude + "," + location.longitude);
        setResult(RESULT_OK, intent);
        finish();
    }

    public void locationFail() {
        DistrictSearch districtSearch = DistrictSearch.newInstance();
        DistrictSearchOption districtSearchOption = new DistrictSearchOption();
        districtSearchOption.cityName(city);

        districtSearch.searchDistrict(districtSearchOption);

        districtSearch.setOnDistrictSearchListener(new OnGetDistricSearchResultListener() {
            @Override
            public void onGetDistrictResult(DistrictResult districtResult) {
                LatLng centerPt = districtResult.getCenterPt();

                if (centerPt != null) {
                    try {
                        MapStatusUpdate msu = MapStatusUpdateFactory.newLatLngZoom(centerPt, 18);
                        mBaiduMap.animateMapStatus(msu);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private LatLng getAddressLatLng() {
        try {
            if (isAddress && lat != null && lng != null) {
                return new LatLng(Double.valueOf(lat), Double.valueOf(lng));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 定位监听
     *
     * @param bdLocation
     */
    @Override
    public void onReceiveLocation(BDLocation bdLocation) {

        //如果bdLocation为空或mapView销毁后不再处理新数据接收的位置
        if (bdLocation == null || mBaiduMap == null) {
            return;
        }

        if (!bdLocation.hasAddr()) {//定位失败

            Log.d("sadfsaf","asfsdfsadfasf");
            if (isFirstCity){
                locationFail();
                isFirstCity = false;
            }
//            if(isAddress) {
//                locationFail();
//            }
            return;
        }
        //定位数据
        MyLocationData data = new MyLocationData.Builder()
                //定位精度bdLocation.getRadius()
                .accuracy(bdLocation.getRadius())
                //此处设置开发者获取到的方向信息，顺时针0-360
                .direction(bdLocation.getDirection())
                //经度
                .latitude(bdLocation.getLatitude())
                //纬度
                .longitude(bdLocation.getLongitude())
                //构建
                .build();

        //设置定位数据
        mBaiduMap.setMyLocationData(data);

        //是否是第一次定位
        if (isFirstLoc) {
            isFirstLoc = false;
            Log.e("isAddress", "isAddress:" + isAddress);
            if (!isAddress) {
                LatLng ll = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
                MapStatusUpdate msu = MapStatusUpdateFactory.newLatLngZoom(ll, 18);
                mBaiduMap.animateMapStatus(msu);
            }
            //获取坐标，待会用于POI信息点与定位的距离
            locationLatLng = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
//            //文本输入框改变监听，必须在定位完成之后
//            etContent.addTextChangedListener(this);
//
//            //创建GeoCoder实例对象
//            geoCoder = GeoCoder.newInstance();
            //发起反地理编码请求(经纬度->地址信息)
            ReverseGeoCodeOption reverseGeoCodeOption = new ReverseGeoCodeOption();
            //设置反地理编码位置坐标
            if (isAddress) {
                LatLng addressLatLng = getAddressLatLng();
                if (addressLatLng != null)
                    reverseGeoCodeOption.location(addressLatLng);
            } else {
                reverseGeoCodeOption.location(new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude()));

            }
            geoCoder.reverseGeoCode(reverseGeoCodeOption);

            //获取城市，待会用于POISearch
            if (!isAddress) {
                city = bdLocation.getCity();
            } else {
                isAddress = false;
            }
            if (city != null) {
                tvCity.setText(city);
            }
        }


    }

    GeoCoder geoCoderVerify;

    public void verifyAddress(final PoiInfo poiInfo) {
        //创建GeoCoder实例对象
        geoCoderVerify = GeoCoder.newInstance();
        //发起反地理编码请求(经纬度->地址信息)
        ReverseGeoCodeOption reverseGeoCodeOption = new ReverseGeoCodeOption();
        //设置反地理编码位置坐标

        reverseGeoCodeOption.location(poiInfo.location);
        geoCoderVerify.reverseGeoCode(reverseGeoCodeOption);

        //设置查询结果监听者
        geoCoderVerify.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
            @Override
            public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
                hideProgressDialog();
                List<PoiInfo> poiInfos = reverseGeoCodeResult.getPoiList();
                //        reverseGeoCodeResult.getAddressDetail().city;
                //限制区域
                ReverseGeoCodeResult.AddressComponent addressDetail = reverseGeoCodeResult.getAddressDetail();
                if (addressDetail != null) {
                    Log.d("city", "location:" + poiInfo.location);
                    Log.d("city", "province1:" + addressDetail.province);
                    Log.d("city", "city1:" + addressDetail.city);
                    Log.d("city", "district1:" + addressDetail.district);

                    String province = addressDetail.province;
                    String city = addressDetail.city;
                    String district = addressDetail.district;

                    loadDetailAddress(province, city, district, poiInfo);
                } else {
                    toast("无法验证址,请稍后再试");
                }


            }
        });


    }

    private void loadDetailAddress(String province, String city, String district, PoiInfo poiInfo) {
        if (district != null && cityDataStr != null) {
            if (cityDataStr.contains(district) && cityDataStr.contains(city) && cityData != null) {
                poiInfo.city = city;

                ArrayList<CityAddressList> addressList = cityData.getAddressList();

                if (addressList != null && addressList.size() > 0) {

                    //获取省级index
                    int index = CityMap.getIndex(addressList, province);
                    if (index > -1) {
                        CityAddressList cityAddressList = addressList.get(index);
                        if (cityAddressList != null) {
                            address.setProvinceName(province);
                            address.setProvinceId(cityAddressList.getCode());
                            ArrayList<CityAddressList> children = cityAddressList.getChildren();
                            if (children != null && children.size() > 0) {
                                //获取市级index
                                int index1 = CityMap.getIndex(children, city);
                                if (index1 > -1) {
                                    CityAddressList cityAddressList1 = children.get(index1);
                                    if (cityAddressList1 != null) {
                                        address.setCityName(city);
                                        address.setCityId(cityAddressList1.getCode());
                                        ArrayList<CityAddressList> children1 = cityAddressList1.getChildren();
                                        if (children1 != null && children1.size() > 0) {
                                            //获取区级index
                                            int index2 = CityMap.getIndex(children1, district);

                                            if (index2 > -1) {
                                                CityAddressList cityAddressList2 = children1.get(index2);
                                                if (cityAddressList2 != null) {
                                                    address.setDistrictName(district);
                                                    address.setDistrictId(cityAddressList2.getCode());
                                                    loadAddress(poiInfo);
                                                    return;
                                                }
                                            }
                                        }
                                    }
                                }


                            }
                        }
                    }

                }

                toast("数据错误");
            } else {
                toast("请选择配送范围内地址");
            }
        }
    }

    //地理编码查询结果回调函数
    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
    }

    //反地理编码查询结果回调函数
    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
        List<PoiInfo> poiInfos = reverseGeoCodeResult.getPoiList();
//        reverseGeoCodeResult.getAddressDetail().city;
        //限制区域
        ReverseGeoCodeResult.AddressComponent addressDetail = reverseGeoCodeResult.getAddressDetail();
        if (addressDetail != null) {
            Log.d("city", "province:" + addressDetail.province);
            Log.d("city", "city:" + addressDetail.city);
            Log.d("city", "district:" + addressDetail.district);

        }
        poiInfo.clear();
        if (poiInfos != null) {
            poiInfo.addAll(poiInfos);
        }
        poiAdapter.notifyDataSetInvalidated();

    }


    /**
     * 手势操作地图，设置地图状态等操作导致地图状态开始改变
     *
     * @param mapStatus 地图状态改变开始时的地图状态
     */
    @Override
    public void onMapStatusChangeStart(MapStatus mapStatus) {
    }

    /**
     * 地图状态变化中
     *
     * @param mapStatus 当前地图状态
     */
    @Override
    public void onMapStatusChange(MapStatus mapStatus) {
    }

    /**
     * 地图状态改变结束
     *
     * @param mapStatus 地图状态改变结束后的地图状态
     */
    @Override
    public void onMapStatusChangeFinish(MapStatus mapStatus) {
        //地图操作的中心点
        LatLng cenpt = mapStatus.target;
        if (geoCoder != null)
            geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(cenpt));
    }

    /**
     * 输入框监听---输入之前
     *
     * @param s     字符序列
     * @param start 开始
     * @param count 总计
     * @param after 之后
     */
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    /**
     * 输入框监听---正在输入
     *
     * @param s      字符序列
     * @param start  开始
     * @param before 之前
     * @param count  总计
     */
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    /**
     * 输入框监听---输入完毕
     *
     * @param s
     */
    @Override
    public void afterTextChanged(Editable s) {
        if (s.length() == 0 || "".equals(s.toString())) {
//            lvSearch.setVisibility(View.GONE);
            poiInfos.clear();
            poiSearchAdapter.notifyDataSetInvalidated();
        } else {
            //创建PoiSearch实例
            PoiSearch poiSearch = PoiSearch.newInstance();
            //城市内检索
            PoiCitySearchOption poiCitySearchOption = new PoiCitySearchOption();
            //关键字
            poiCitySearchOption.keyword(s.toString());
            //城市
            poiCitySearchOption.city(tvCity.getText().toString());

            //设置每页容量，默认为每页10条
            poiCitySearchOption.pageCapacity(10);
//            //分页编号
//            poiCitySearchOption.pageNum(1);
            poiSearch.searchInCity(poiCitySearchOption);
            //设置poi检索监听者
            poiSearch.setOnGetPoiSearchResultListener(new OnGetPoiSearchResultListener() {
                //poi 查询结果回调
                @Override
                public void onGetPoiResult(PoiResult poiResult) {
                    if (etContent.length() == 0 || "".equals(etContent.getText().toString().trim())) {

                        poiInfos.clear();
                        poiSearchAdapter.notifyDataSetInvalidated();
                        return;
                    }
                    List<PoiInfo> pois = poiResult.getAllPoi();
                    poiInfos.clear();
                    if (pois != null) {
                        poiInfos.addAll(pois);
                    }

                    poiSearchAdapter.setLocationLatLng(locationLatLng);
                    lvSearch.setVisibility(View.VISIBLE);
                    poiSearchAdapter.notifyDataSetInvalidated();

                }

                //poi 详情查询结果回调
                @Override
                public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

                }

                @Override
                public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

                }
            });
        }
    }


    //回退键
    @Override
    public void onBackPressed() {
        if (lvSearch.getVisibility() == View.VISIBLE) {
            lvSearch.setVisibility(View.GONE);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // activity 恢复时同时恢复地图控件
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        // activity 暂停时同时暂停地图控件
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //退出时停止定位
        if (mLocClient != null)
            mLocClient.stop();
        //退出时关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);

        // activity 销毁时同时销毁地图控件
        mMapView.onDestroy();

        //释放资源
        if (geoCoder != null) {
            geoCoder.destroy();
        }
        if (geoCoderVerify != null) {
            geoCoderVerify.destroy();
        }

        mMapView = null;
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.et_content:
                lvSearch.setVisibility(View.VISIBLE);
                break;
            case R.id.iv_location:
                isFirstLoc = true;
                if (mLocClient != null)
                    mLocClient.requestLocation();
                break;
            case R.id.tv_city:

                if (isLimit) {
                    if (cityData == null || cityData.getAddressList() == null || cityData.getAddressList().size() == 0) {
                        requestArea();
                    } else if (cityData != null) {
                        openArea();
                    }
                } else {
                    openArea();
                }
                break;
            default:
                break;
        }
    }


    CityMap cityData;
    Address address = new Address();

    public void openArea() {
        AreaDialog areaDialog = new AreaDialog(this);
        if (cityData == null)
            cityData = areaDialog.getCityData();
        areaDialog.setPositiveDismiss(true);


        areaDialog.setCurrentIndex(cityData, address.getProvinceId(), address.getCityId(), address.getDistrictId());
        areaDialog.setOnPositiveClickListener(new AreaDialog.OnPositiveClickListener() {

            @Override
            public void onPositiveClickListener(int index1, CityAddressList city1, int index2, CityAddressList city2, int index3, CityAddressList city3) {
                if (city1 != null && city2 != null && city3 != null) {
                    address.setProvinceId(city1.getCode());
                    address.setCityId(city2.getCode());
                    address.setDistrictId(city3.getCode());

                    address.setProvinceName(city1.getName());
                    address.setCityName(city2.getName());
                    address.setDistrictName(city3.getName());


                    tvCity.setText(city2.getName());
                    city = city2.getName();


                    Log.d("city", "city1:" + city);
                    Log.d("city", "city2:" + city3.getName());
                    DistrictSearch districtSearch = DistrictSearch.newInstance();
                    DistrictSearchOption districtSearchOption = new DistrictSearchOption();
                    districtSearchOption.cityName(city);
                    if (!"市辖区".equals(city3.getName()))
                        districtSearchOption.districtName(city3.getName());
                    districtSearch.searchDistrict(districtSearchOption);

                    districtSearch.setOnDistrictSearchListener(new OnGetDistricSearchResultListener() {
                        @Override
                        public void onGetDistrictResult(DistrictResult districtResult) {
                            LatLng centerPt = districtResult.getCenterPt();

                            if (centerPt != null) {
                                MapStatusUpdate msu = MapStatusUpdateFactory.newLatLngZoom(centerPt, 18);
                                mBaiduMap.animateMapStatus(msu);
                            }
                        }
                    });

                }
            }
        });
        areaDialog.show();
    }


    private OnRequestListener<CityMap> onRequestAreaListener = new OnRequestListener<CityMap>() {
        @Override
        public CityMap jsonToObj(String s) {
            return new Gson().fromJson(s, CityMap.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {

        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {

        }

        @Override
        public void onStart(Object o) {

        }

        @Override
        public void onResponse(ResponseEntity<CityMap> responseEntity, Object o) {

            CityMap responseElement = responseEntity.getResponseElement();
            if (responseElement != null && responseElement.getAddressList() != null && responseElement.getAddressList().size() > 0) {
                cityData = responseElement;
                openArea();
            }

        }
    };

    public void requestArea() {
        RequestEntityMapSupply re = new RequestEntityMapSupply();
        //re.setCmd("address/findCityDisArea");
        re.setCmd(AppPurchaseRouterConstant.cmd_account_app_deliveryAddress);
        request(re, AppPurchaseRouterConstant.cmd_account_app_deliveryAddress, onRequestAreaListener);
    }

}
